<template>
  <div class="work-detail-container">
    <el-page-header title="返回" @back="goBack" content="作品详情" />
    <el-card v-if="work" class="work-detail-card">
      <template #header>
        <div class="work-header">
          <h1 class="work-title">{{ work.title }}</h1>
          <el-button 
            type="primary" 
            :icon="isPlaying ? 'VideoPause' : 'VideoPlay'" 
            @click="togglePlay"
            :loading="isPreparing"
            circle
          />
        </div>
      </template>
      
      <div class="work-info">
        <el-row :gutter="20">
          <el-col :span="24" :md="6">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span class="info-label">作者:</span>
              <span class="info-value">{{ work.author.name }}</span>
            </div>
          </el-col>
          <el-col :span="24" :md="6" v-if="work.author.dynasty">
            <div class="info-item">
              <el-icon><Location /></el-icon>
              <span class="info-label">朝代:</span>
              <span class="info-value">{{ work.author.dynasty }}</span>
            </div>
          </el-col>
          <el-col :span="24" :md="6" v-if="work.genre">
            <div class="info-item">
              <el-icon><Collection /></el-icon>
              <span class="info-label">类型:</span>
              <span class="info-value">{{ work.genre }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <div class="work-content">
        <h2>作品内容</h2>
        <div class="content-text" v-html="work.content"></div>
      </div>
      
      <div v-if="work.background" class="work-background">
        <h2>创作背景</h2>
        <div class="background-text" v-html="work.background"></div>
      </div>
      
      <div v-if="work.meaning" class="work-background">
        <h2>表达含义</h2>
        <div class="background-text" v-html="work.meaning"></div>
      </div>

      <div v-if="work.annotation" class="work-background">
        <h2>内容注释</h2>
        <div class="background-text" v-html="work.annotation"></div>
      </div>

      <div class="work-background">
        <h2>作者简介</h2>
        <div class="background-text" v-html="work.author.intro"></div>
      </div>
    </el-card>
    
    <div v-else-if="loading" class="loading-container">
      <el-skeleton animated>
        <template #template>
          <el-card>
            <template #header>
              <el-skeleton-item variant="h1" style="width: 60%" />
            </template>
            <el-skeleton-item variant="text" style="width: 30%" />
            <br />
            <el-skeleton-item variant="text" style="width: 40%" />
            <br />
            <el-skeleton-item variant="text" style="width: 90%" />
            <br />
            <el-skeleton-item variant="text" style="width: 80%" />
          </el-card>
        </template>
      </el-skeleton>
    </div>
    
    <el-empty v-else description="作品不存在" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getWork } from '@/api/works'
import type { LiteraryWork } from '@/types'

defineProps<{
  id: string
}>()

const route = useRoute()
const router = useRouter()
const work = ref<LiteraryWork | null>(null)
const loading = ref(true)

const isPlaying = ref(false)
const isPreparing = ref(false)
let speechSynthesis: SpeechSynthesis | null = null
let utterance: SpeechSynthesisUtterance | null = null

onMounted(async () => {
  const workId = parseInt(route.params.id as string)
  
  try {
    work.value = await getWork(workId)
  } catch (error) {
    console.error('获取作品详情失败:', error)
  } finally {
    loading.value = false
  }

  if ('speechSynthesis' in window) {
    speechSynthesis = window.speechSynthesis
  } else {
    console.warn('当前浏览器不支持文字转语音功能')
  }
})

onUnmounted(() => {
  // 组件销毁时停止播放
  if (speechSynthesis && isPlaying.value) {
    speechSynthesis.cancel()
  }
})

const togglePlay = () => {
  if (!work.value) return
  
  // 如果正在播放，则暂停
  if (isPlaying.value) {
    pausePlay()
  } 
  // 如果已暂停，则重新开始播放
  else if (speechSynthesis && speechSynthesis.paused) {
    speechSynthesis.resume()
    isPlaying.value = true
  }
  // 如果没有在播放或暂停，则开始新的播放
  else {
    startPlay()
  }
}

const startPlay = () => {
  if (!speechSynthesis) {
    console.warn('浏览器不支持文字转语音功能')
    return
  }
  
  // 如果当前有正在播放或暂停的语音，先取消它
  if (speechSynthesis.speaking) {
    speechSynthesis.cancel()
  }
  
  isPreparing.value = true
  
  // 构造要朗读的文本内容
  let textToRead = `${work.value.title}, 作者: ${work.value.author.name}，${work.value.author.dynasty}，${work.value.genre}`
  
  // 移除HTML标签，只保留纯文本
  const contentText = work.value.content.replace(/<[^>]*>/g, '')
  textToRead += `作品内容: ${contentText}`
  
  if (work.value.background) {
    const backgroundText = work.value.background.replace(/<[^>]*>/g, '')
    textToRead += `创作背景: ${backgroundText}`
  }
  
  if (work.value.meaning) {
    const meaningText = work.value.meaning.replace(/<[^>]*>/g, '')
    textToRead += `表达含义: ${meaningText}`
  }
  
  // 创建新的语音合成对象
  utterance = new SpeechSynthesisUtterance(textToRead)
  
  // 设置语音参数
  utterance.rate = 1.0  // 语速
  utterance.pitch = 1.0 // 音调
  utterance.volume = 1.0 // 音量
  
  // 选择一个自然的语音
  const voices = speechSynthesis.getVoices()
  const chineseVoice = voices.find(voice => voice.lang.includes('zh'))
  if (chineseVoice) {
    utterance.voice = chineseVoice
  }
  
  // 设置事件监听器
  utterance.onstart = () => {
    isPreparing.value = false
    isPlaying.value = true
  }
  
  utterance.onend = () => {
    isPlaying.value = false
  }
  
  utterance.onerror = (event) => {
    console.error('语音播放出错:', event)
    isPlaying.value = false
    isPreparing.value = false
  }
  
  // 开始播放
  speechSynthesis.speak(utterance)
}

const pausePlay = () => {
  if (speechSynthesis && isPlaying.value) {
    speechSynthesis.pause()
    isPlaying.value = false
  }
}

// 修改goBack函数
const goBack = () => {
  // 返回前停止播放
  if (speechSynthesis && isPlaying.value) {
    speechSynthesis.cancel()
  }
  router.go(-1)
}
</script>

<style scoped>
.work-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.el-page-header {
  margin-bottom: 20px;
}

.work-detail-card {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  backdrop-filter: blur(10px);
  border: 1px solid var(--border-color);
  border-radius: 15px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.work-detail-card:hover {
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
  transform: translateY(-5px);
}

.work-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.work-title {
  margin: 0;
  color: var(--text-color);
  font-size: 2em;
  font-weight: bold;
}

.work-info {
  margin-bottom: 30px;
  padding: 20px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  border: 1px solid var(--border-color);
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.info-item .el-icon {
  color: var(--el-color-primary);
  font-size: 18px;
}

.info-label {
  font-weight: 500;
  margin-right: 8px;
  color: var(--text-color);
  min-width: 50px;
}

.info-value {
  color: var(--text-color);
}

.work-content, .work-background {
  padding: 25px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  border-radius: 12px;
  margin-bottom: 25px;
  border: 1px solid var(--border-color);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.work-content:hover, .work-background:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.work-content h2, .work-background h2 {
  margin-top: 0;
  color: var(--text-color);
  border-bottom: 2px solid var(--el-color-primary);
  padding-bottom: 10px;
  text-align: left;
  font-size: 1.5em;
  position: relative;
}

.work-content h2:before, .work-background h2:before {
  content: "";
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 50px;
  height: 2px;
  background: var(--el-color-primary);
}

.content-text, .background-text, .meaning-text {
  white-space: pre-wrap;
  line-height: 1.8;
  color: var(--text-color);
  font-size: 16px;
  text-align: left;
}

.loading-container {
  max-width: 800px;
  margin: 0 auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .work-detail-container {
    padding: 10px;
  }
  
  .work-title {
    font-size: 1.5em;
  }
  
  .work-info {
    padding: 15px;
  }
  
  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .info-item .el-icon {
    margin-bottom: 4px;
  }
  
  .work-content, .work-background {
    padding: 15px;
  }
  
  .content-text, .background-text, .meaning-text {
    font-size: 14px;
  }
}

.work-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.work-title {
  margin: 0;
  color: var(--text-color);
  font-size: 2em;
  font-weight: bold;
  flex-grow: 1;
}

:deep(.el-page-header__content) {
  color: var(--text-color);
  font-weight: 500;
}

:deep(.el-page-header__title) {
  color: var(--text-color);
  opacity: 0.8;
}

/* 确保在暗色主题下也能正确显示 */
[data-theme="dark"] :deep(.el-page-header__content),
[data-theme="dark"] :deep(.el-page-header__title) {
  color: var(--text-color);
}
</style>